package com.doubi.utils;

import org.apache.commons.io.IOUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class VideoProcessing {

    private static FFmpegFrameGrabber fFmpegFrameGrabber;

    public void init(String videoFileName) throws Exception {
        fFmpegFrameGrabber = new FFmpegFrameGrabber(getInputStreamByUrl(videoFileName));
        fFmpegFrameGrabber.start();
    }

    public double getTime() {
        int ftp = fFmpegFrameGrabber.getLengthInFrames();
        double res  = ftp / fFmpegFrameGrabber.getFrameRate() / 60 ;
        return (double) Math.round(res * 100) / 100;
    }

    public InputStream grabberVideoFramer() throws Exception {
        //Frame对象
        Frame frame = null;
        //标识
        int flag = 0;
			 /*
            获取视频文件
            */
        //获取视频总帧数
        int ftp = fFmpegFrameGrabber.getLengthInFrames();
        System.out.println("这个视频共有" + ftp + "针");
        while (flag <= ftp) {
            if (flag == 5) {
                frame = fFmpegFrameGrabber.grabImage();
				/*
				对视频的第五帧进行处理
				 */
                if (frame != null) {
                    BufferedImage bufferedImage = FrameToBufferedImage(frame);
                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
                    ImageIO.write(bufferedImage, "jpg", imOut);
                    return new ByteArrayInputStream(bs.toByteArray());
                }
            }
            flag++;
        }
        fFmpegFrameGrabber.stop();
        fFmpegFrameGrabber.close();
        return null;
    }

    private static BufferedImage FrameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        return converter.getBufferedImage(frame);
    }

    /**
     * 根据地址获得数据的输入流
     *
     * @param strUrl 网络连接地址
     * @return url的输入流
     */
    private static InputStream getInputStreamByUrl(String strUrl) throws Exception {
        HttpURLConnection conn = null;
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(20 * 1000);
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), output);
        conn.disconnect();
        return new ByteArrayInputStream(output.toByteArray());
    }
}
